package me.xue.communityhealth.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author lee
 * @version 1.0
 * @since 2017/2/16
 */

public final class Md5Util {

    /**
     *Get the unique string of orig with md5 algorithm.
     * @param orig The original string.
     * @return The unique result string of s.
     */
    public static String getHashKey(String orig) {
        String hashKey;
        try {
            final MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(orig.getBytes());
            hashKey = bytesToHexString(md.digest());
        } catch (NoSuchAlgorithmException e) {
            hashKey = String.valueOf(orig.hashCode());
        }
        return hashKey;
    }

    private static String bytesToHexString(byte[] digests) {
        StringBuilder sb = new StringBuilder();
        for (byte b : digests) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

}
